from wxpy import *

from Quant import Quant

GROUP_NAME="通知群"
# GROUP_NAME="量化通知"
class QuantBot:
    def __init__(self,bot,quant):
        self.bot = bot
        self.quant = quant
        self.notice_group = bot.groups().search(GROUP_NAME)[0]

    def send_notice(self,text):
        self.notice_group.send(text)

    def handle_group_msg(self,msg):
        print(f"msg group:{isinstance(msg.chat, Group)} at:{msg.is_at} text:{msg.text} type:{msg.type} member:{msg.member.nick_name}")

        if (not isinstance(msg.chat, Group)):
            return

        if not msg.is_at:
            return

        if msg.sender.nick_name!=GROUP_NAME:
            return

        strs = msg.text.split()
        if strs[1] == "1000":
            return self.handle_1000(strs)
        if strs[1] == "1001":
            return self.handle_1001(strs)
        if strs[1] == "1002":
            return self.handle_1002(strs)
        else:
            return self.handle_unknown(strs)

    def handle_1000(self,strs):
        strs=""
        for s in self.quant.securitys.keys():
            security = self.quant.securitys[s]
            strs += f"{security['code']} " \
                    f"{security['name']} " \
                    f"现:{security['price']} " \
                    f"前:{security['price_last']}" \
                    f"支:{security['support']} " \
                    f"阻:{security['resistance']}" \
                    f"昨收:{security['last_close']} " \
                    f"今开:{security['today_open']} " \
                    f"高:{security['high']} " \
                    f"低:{security['low']} " \
                    f"\n\n"
        self.send_notice(strs)

    def handle_1001(self,strs):
        if len(strs)!=3:
            self.send_tips()
            return

        security = strs[2]
        self.quant.add_security(security)
        self.send_notice(f"添加{security}完成")

    def handle_1002(self,strs):
        if len(strs)!=3:
            self.send_tips()
            return

        security = strs[2]
        self.quant.remove_security(security)
        self.send_notice(f"移除{security}完成")

    def handle_unknown(self,strs):
        self.send_tips()
    def send_tips(self):
        self.send_notice("命令格式:\n"
                         "1000:查看所有监控\n"
                         "1001：增加监控股票\n"
                         "1002：删除监控股票")



bot = Bot(cache_path=True,qr_path='QR.png')
# 机器人账号自身
myself = bot.self
# 向文件传输助手发送消息
bot.file_helper.send('Hello from wxpy!')

quant = Quant()
quantBot = QuantBot(bot,quant)
quant.setQuantBot(quantBot)
quant.run_in_thread()

@bot.register(Group, TEXT)
def handle_group_msg(msg):
    quantBot.handle_group_msg(msg)

embed()
